﻿using IceDog.UpdateDB.IRepository;
using IceDog.UpdateDB.Model;
using IceDog.UpdateDB.Model.Data;
using IceDog.UpdateDB.Model.SingleModel;
using IceDog.UpdateDB.Repository;
using IceDog.UpdateDB.WebServer.Filters;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using System;
using System.IO;
using System.Reflection;

namespace IceDog.UpdateDB.WebServer
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(opts =>
            {
                opts.EnableEndpointRouting = true;
                opts.Filters.Add<AuthorizationFilter>();
                opts.Filters.Add<UserActionFilter>();

            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            var connectionString = Configuration.GetConnectionString("SqliteConn");
            services.AddDbContextPool<EFContext>(options =>
            {
                options.UseSqlite(connectionString);
            });

            services.AddSingleton<Func<EFContext>>(() =>
            {
                var optionsBuilder = new DbContextOptionsBuilder<EFContext>();
                optionsBuilder.UseSqlite(connectionString);
                //如果有其他依赖的话，可以通过provider.GetService<XX>()来获取
                //var provider = services.BuildServiceProvider();
                //provider.GetService<xx>();
                return new EFContext(optionsBuilder.Options);
            });

            InjectInstance(services);

            AddSwashbuckle(services);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseRouting();
            app.UseEndpoints(configure =>
            {
                configure.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseAuthorization();
            app.UseStaticFiles();
            UseSwashbuckle(app);
        }
        private void InjectInstance(IServiceCollection services)
        {
            services.AddSingleton(typeof(WindowsOSInfo));

            services.AddScoped<IUsersRepository, UsersRepository>();
        }
        private void AddSwashbuckle(IServiceCollection services)
        {
            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo()
                {
                    Title = "DB API v1.0",
                    Description = "制造数据API",
                    License = new OpenApiLicense()
                    {
                        Name = "GPL v3",
                        Url = new Uri("http://www.example.com/gplv3")
                    },
                    Contact = new OpenApiContact()
                    {
                        Name = "dhclly",
                        Email = "335121817@qq.com",
                        Url = new Uri("http://www.example.com/dhclly")
                    },
                    Version = "v1.0",
                    TermsOfService = new Uri("http://www.example.com/help")
                });
                //options.OperationFilter<HiddenApi>();

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{typeof(BaseModel).Assembly.GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath);
                options.DocumentFilter<HiddenApiFilter>();
            });
        }

        private void UseSwashbuckle(IApplicationBuilder app)
        {
            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(setup =>
            {
                setup.RoutePrefix = "api-list";//设置为根目录
                setup.SwaggerEndpoint("/swagger/v1/swagger.json", "DB API v1.0");

            });
        }
    }
}
